package com.ctshk.rpc.order.goods.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SmsType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.ShareCodeUtil;
import com.ctshk.rpc.order.goods.dto.*;
import com.ctshk.rpc.order.goods.dto.es.CommodityOrderDetailEsDTO;
import com.ctshk.rpc.order.goods.entity.ShoppingShopStore;
import com.ctshk.rpc.order.goods.mapper.ShoppingShopMapper;
import com.ctshk.rpc.order.goods.mapper.ShoppingShopStoreMapper;
import com.ctshk.rpc.order.goods.req.ShopCustomerOrderReq;
import com.ctshk.rpc.order.goods.req.ShoppingShopStoreAddReq;
import com.ctshk.rpc.order.goods.req.ShoppingShopStorePageReq;
import com.ctshk.rpc.order.goods.service.IShoppingShopStoreService;
import com.ctshk.rpc.user.dto.es.OrderEsDTO;
import com.ctshk.rpc.user.req.OrderPageReq;
import com.ctshk.rpc.user.service.IOrderEsService;
import com.ctshk.rpc.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商城小店--实现类
 * </p>
 *
 * @author 黄利斌
 * @date 2021/6/1 4:22 下午
 */
@Slf4j
@DubboService
public class ShoppingShopStoreServiceImpl extends ServiceImpl<ShoppingShopStoreMapper, ShoppingShopStore> implements IShoppingShopStoreService {

    @Autowired
    private ShoppingShopStoreMapper shopStoreMapper;

    @Autowired
    private ShoppingShopStoreMapper shoppingShopStoreMapper;

    @Autowired
    private ShoppingShopMapper shoppingShopMapper;

    /**
     * 根据邀请码获取小店来源
     *
     * @param code
     * @param name
     * @return
     */
    @Override
    public Result<Map<String, Object>> invitation(String code, String name) {
        log.info("【中旅小店--邀请码获取小店来源--start】，入参为 -- code:{},name:{}", code, name);
        if (null == name) {
            return Result.failed(SystemError.SYS_402);
        }
        ShoppingShopStore shoppingShopStore = new ShoppingShopStore();
        Long id = 0L;
        String customerServiceHotline = "";
        if (!StringUtils.isEmpty(code)) {
            // 查询小店来源id
//            id = shoppingShopStoreMapper.selectOne(new QueryWrapper<ShoppingShopStore>().lambda().eq(ShoppingShopStore::getStoreInvitationCode, code).eq(ShoppingShopStore::getStoreName, name)).getId();
            shoppingShopStore = shoppingShopStoreMapper.selectShopByCodeAndName(code, name);
//            id = shoppingShopStore.getId();
//            customerServiceHotline = shoppingShopStore.getCustomerServiceHotline();

        } else {
            // 查询商城来源id
//            id = shoppingShopMapper.selectOne(new QueryWrapper<ShoppingShop>().lambda().eq(ShoppingShop::getShopName, name)).getId();
            shoppingShopStore = shoppingShopStoreMapper.selectShopByName(name);
//            id = shoppingShopStore.getId();
//            customerServiceHotline = shoppingShopStore.getCustomerServiceHotline();
        }
        id = shoppingShopStore.getId();
        customerServiceHotline = shoppingShopStore.getCustomerServiceHotline();
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("customerServiceHotline", customerServiceHotline);
        log.info("【中旅小店--邀请码获取小店来源--end】");
        return Result.success(map);
    }

    @Override
    public void staff(ShoppingShopStoreAddReq req, Long userId, ShoppingShopStoreDTO shoppingShopStoreDTO) {
        log.info("【中旅小店--开通成员小店--start】,入参为 -- req:{},userId:{},ShoppingShopStoreDTO:{}", JSON.toJSONString(req), userId, JSON.toJSONString(shoppingShopStoreDTO));
        // 判断当前用户是否内部人员，内部人员的话，电邮为组织架构内的电邮
        // 邀请码
        String storeInvitationCode = ShareCodeUtil.idToCode(req.getStaffId());
        ShoppingShopStore shopStore = new ShoppingShopStore();
        BeanUtils.copyProperties(req, shopStore);
        LocalDateTime now = LocalDateTime.now();
        shopStore.setId(null);
        //邀请码
        shopStore.setStoreInvitationCode(storeInvitationCode);
        // 总店id
        shopStore.setStoreId(req.getId());
        // 创建人
        shopStore.setCreateId(userId);
        // 创建时间
        shopStore.setGmtCreate(now);
        // 修改人
        shopStore.setModifiedId(userId);
        // 修改时间
        shopStore.setGmtModified(now);
        shopStore.setIsDeleted(IsDeletedCode.NO.getCode());
        // 	固定2,2为成员
        shopStore.setStaffType(2);
        // 	0：无效;	1：有效
        shopStore.setStatus(1);
        // 固定2,2为分店
        shopStore.setStoreType(2);
        log.info("【中旅小店--开通成员小店--新增】，入参为:{}", shopStore);
        shopStoreMapper.insert(shopStore);
        log.info("【中旅小店--开通成员小店--end】");
    }

    @Override
    public void updateShoppingShopStore(ShoppingShopStoreAddReq obj, ShoppingShopStoreDTO shoppingShopStoreDTO) {
        log.info("【中旅小店--编辑小店--start】，入参为 -- obj:{},shoppingShopStoreDTO:{}", JSON.toJSONString(obj), JSON.toJSONString(shoppingShopStoreDTO));
        if (null == shoppingShopStoreDTO) {
            throw new BusinessException(SystemError.GOODS_SHOP_ERROR_40011);
        }
        ShoppingShopStore shopStore = shopStoreMapper.selectById(obj.getId());
        BeanUtils.copyProperties(obj, shopStore, EntityUtil.getNullPropertyNames(obj));
        LocalDateTime now = LocalDateTime.now();
        shopStore.setModifiedId(shoppingShopStoreDTO.getId());
        shopStore.setGmtModified(now);
        log.info("【中旅小店--编辑小店--更新小店信息】，入参为:{}", shopStore);
        shopStoreMapper.updateById(shopStore);
        log.info("【中旅小店--编辑小店--end】");
    }

    @Override
    public Result<PageResponse<ShoppingShopStoreDTO>> findShoppingShopStoreByCondition(ShoppingShopStorePageReq pageReq, ShoppingShopStoreDTO shoppingShopStoreDTO) {
        log.info("【中旅小店--分页查询成员管理列表--start】，入参为 -- ShoppingShopStorePageReq:{},ShoppingShopStoreDTO:{}", JSON.toJSONString(pageReq), JSON.toJSONString(shoppingShopStoreDTO));
        if (null == shoppingShopStoreDTO) {
            return Result.failed(SystemError.GOODS_SHOP_ERROR_40011);
        }
        IPage<ShoppingShopStoreDTO> page = new Page<ShoppingShopStoreDTO>(pageReq.getPageNo(), pageReq.getPageSize());
        IPage<ShoppingShopStoreDTO> iPage = shopStoreMapper.findShoppingShopStoreByCondition(page, pageReq);
        List<ShoppingShopStoreDTO> shoppingShopStoreList = iPage.getRecords();
        List<ShoppingShopStoreDTO> pageDTOList = EntityUtil.copyList(shoppingShopStoreList, ShoppingShopStoreDTO.class);
        log.info("【中旅小店--分页查询成员管理列表--end】");
        return Result.success(new PageResponse<>(pageDTOList, iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(), iPage.getSize()));
    }

    @Override
    public Result<ShoppingShopStoreDTO> info(Long id, ShoppingShopStoreDTO shoppingShopStoreUser) {
        log.info("【中旅小店--获取头部信息--start】，入参为 -- id:{},shoppingShopStoreUser:{}", id, JSON.toJSONString(shoppingShopStoreUser));
        if (null == shoppingShopStoreUser) {
            return Result.failed(SystemError.GOODS_SHOP_ERROR_40011);
        }
        ShoppingShopStore shoppingShopStore = shoppingShopStoreMapper.selectShopById(id);
        ShoppingShopStoreDTO shoppingShopStoreDTO = EntityUtil.copy(shoppingShopStore, ShoppingShopStoreDTO.class);
        log.info("【中旅小店--获取头部信息--end】");
        return Result.success(shoppingShopStoreDTO);
    }

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result sendSmsCaptcha(String contactMobileAreaCode, String contactNumber, Integer type, Long userId) {
        boolean isNotBlankContactNumber = true;
        if (SmsType.UPDATE_PWD.getType().equals(type) || (SmsType.UPDATE_PHONE.getType().equals(type) && StringUtils.isBlank(contactMobileAreaCode)
                && StringUtils.isBlank(contactNumber))) {
            isNotBlankContactNumber = false;
//            UserDTO userDTO = userService.queryCacheUser(userId);
//            contactMobileAreaCode = userDTO.getContactMobileAreaCode();
//            contactNumber = userDTO.getContactNumber();
        }
        String fullContactNumber = contactMobileAreaCode + contactNumber;
        String key = RedisConstants.SMS_CODE_KEY + fullContactNumber + "_" + type;
        Object o = redisTemplate.opsForValue().get(key);

        if (o != null) {
            // 短信间隔两分钟可重发
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (expire > 180) {
                throw new BusinessException(SystemError.USER_1019);
            }
        }

        String code = RandomUtil.randomNumbers(4);
//        try {
        // 根据验证码类型选择不同的短信模板
//            if(SmsType.LOGIN.getType().equals(type)) {
//                if(SmsUtil.isDomestic(contactMobileAreaCode)) {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getLoginTemplateCode(),code);
//                } else {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getInternationalLoginTemplateCode(),code);
//                }
//
//            } else if (SmsType.REGISTER.getType().equals(type)) {
//                // 注册需要判断该手机号是否已注册过
//                UserDTO userDTO = new UserDTO();
//                userDTO.setContactMobileAreaCode(contactMobileAreaCode);
//                userDTO.setContactNumber(contactNumber);
//                boolean exists = userService.exists(userDTO);
//                if(exists) {
//                    return Result.failed(new BusinessException(SystemError.SYS_433,"手机号已被注册"));
//                }
//                if(SmsUtil.isDomestic(contactMobileAreaCode)) {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getRegiterTemplateCode(),code);
//                } else {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getInternationalRegiterTemplateCode(),code);
//                }
//
//            } else if (SmsType.RESET_PWD.getType().equals(type)) {
//                if(SmsUtil.isDomestic(contactMobileAreaCode)) {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getResetPwdTemplateCode(),code);
//                } else {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getInternationalResetPwdTemplateCode(),code);
//                }
//            } else if (SmsType.UPDATE_PHONE.getType().equals(type)) {
//                if(isNotBlankContactNumber) {
//                    // 修改手机时需要判断该手机号是否已注册过
//                    UserDTO userDTO = new UserDTO();
//                    userDTO.setContactMobileAreaCode(contactMobileAreaCode);
//                    userDTO.setContactNumber(contactNumber);
//                    boolean exists = userService.exists(userDTO);
//                    if(exists) {
//                        return Result.failed(new BusinessException(SystemError.SYS_433,"手机号已被注册"));
//                    }
//                }
//                if(SmsUtil.isDomestic(contactMobileAreaCode)) {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getUpdatePhoneTemplateCode(),code);
//                } else {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getInternationalUpdatePhoneTemplateCode(),code);
//                }
//            } else if (SmsType.UPDATE_PWD.getType().equals(type)) {
//                if(SmsUtil.isDomestic(contactMobileAreaCode)) {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getUpdatePwdTemplateCode(),code);
//                } else {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getInternationalUpdatePwdTemplateCode(),code);
//                }
//            } else if (SmsType.GENERAL.getType().equals(type)) {
//                if(SmsUtil.isDomestic(contactMobileAreaCode)) {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getGeneralTemplateCode(),code);
//                } else {
//                    SmsUtil.sendSmsCode(fullContactNumber,smsConfig.getInternationalGeneralTemplateCode(),code);
//                }
//            }else {
//                throw new BusinessException(SystemError.USER_1021);
//            }
//        } catch (Exception e) {
//            throw new BusinessException(SystemError.SYS_433,e.getMessage());
//        }

        //发送短信成功清除错误次数
        String errCountKey = RedisConstants.SMS_ERR_COUNT_CODE_KEY + fullContactNumber + "_" + type;
        redisTemplate.delete(errCountKey);
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
        return Result.success();
    }

    @DubboReference
    private IOrderEsService orderEsService;

    @DubboReference
    private IUserService userService;

    @Override
    public Result<StoreShopDTO> show(Long id, Integer type, ShoppingShopStoreDTO shoppingShopStoreDTO) {
        log.info("【中旅商城--app小店--销售额、订单、客户数--start】，入参为 -- id:{},type:{},shoppingShopStoreDTO:{}", id, type, JSON.toJSONString(shoppingShopStoreDTO));
        if (null == shoppingShopStoreDTO) {
            return Result.failed(SystemError.GOODS_SHOP_ERROR_40011);
        }
        if (null == type) {
            type = 6;
        }
        StoreShopDTO storeShopDTO = new StoreShopDTO();
        List<OrderShopCustomerDTO> orderShopCustomerDTOList = new ArrayList<>();
        // ES查询条件
        OrderPageReq req = new OrderPageReq();
        req.setGmtCreateType(type);
        req.setShopId(id);
        try {
            Result<PageResponse<OrderEsDTO>> pageResponseResult = orderEsService.queryPage(req);
            if (pageResponseResult.getCode() == 0 && pageResponseResult.getMsg().equalsIgnoreCase("成功")) {
                PageResponse<OrderEsDTO> pageResponseResultData = pageResponseResult.getData();
                // 销售总金额
                BigDecimal totalAmount = new BigDecimal("0");
                // 成交量
                Long volume = pageResponseResultData.getTotal();
                // 客户数
                Integer customerNumber = 0;

                // 单个用户累计成交金额
                Map<Object, Object> map = new HashMap<Object, Object>();

                for (OrderEsDTO record : pageResponseResultData.getRecords()) {
                    // 获取订单总金额
                    totalAmount = totalAmount.add(record.getOrderAmount());
                    OrderShopCustomerDTO orderShopCustomerDTO = EntityUtil.copy(record, OrderShopCustomerDTO.class);
                    orderShopCustomerDTOList.add(orderShopCustomerDTO);
                }
//                orderShopCustomerDTOList = orderShopCustomerDTOList.stream().distinct().collect(Collectors.toList());
                customerNumber = orderShopCustomerDTOList.size();
                storeShopDTO.setVolume(volume);
                storeShopDTO.setCustomerNumber(customerNumber);
                storeShopDTO.setTotalAmount(totalAmount);
//                storeShopDTO.setOrderShopCustomerDTOList(orderShopCustomerDTOList);
                return Result.success(storeShopDTO);
            }
        } catch (Exception e) {
            log.error("【中旅商城--app小店--获取es订单数据错误】------错误为：{}", e.getMessage());
        }
        log.info("【中旅商城--app小店--销售额、订单、客户数--end】");
        return Result.failed(SystemError.GOODS_SHOP_ERROR_40016);
    }

    @Override
    public Result<PageResponse<ShopOrderEsDTO>> customerOrder(ShopCustomerOrderReq req, ShoppingShopStoreDTO shoppingShopStoreDTO) {
        log.info("【中旅商城--app小店--客户订单--start】,入参为 -- ShopCustomerOrderReq:{},ShoppingShopStoreDTO:{}", JSON.toJSONString(req), JSON.toJSONString(shoppingShopStoreDTO));
        if (null == shoppingShopStoreDTO) {
            return Result.failed(SystemError.GOODS_SHOP_ERROR_40011);
        }
        IPage<ShopOrderEsDTO> iPage = new Page<>(req.getPageNo(), req.getPageSize());
        // 查询es的小店所有订单数据
        OrderPageReq pageReq = new OrderPageReq();
        pageReq.setShopId(req.getShopId());
        // 类型 1：代付款、2：已付款、3：已取消、5：退款/售后
        pageReq.setFilterOrderStatus(req.getType());
        pageReq.setPageNo(req.getPageNo());
        pageReq.setPageSize(req.getPageSize());
        // 订单号
        pageReq.setOrderNumber(req.getOrderNumber());
        if (null != req.getYearOfMonth()) {
            pageReq.setGmtCreateType(null);
        }
        // 订单创建年月
        pageReq.setYearOfMonth(req.getYearOfMonth());
        try {
            Result<PageResponse<OrderEsDTO>> pageResponseResult = orderEsService.queryPage(pageReq);
            if (pageResponseResult.getCode() == 0 && pageResponseResult.getMsg().equalsIgnoreCase("成功")) {
                List<ShopOrderEsDTO> orderEsDTOList = new ArrayList<>();
                for (OrderEsDTO record : pageResponseResult.getData().getRecords()) {
                    ShopOrderEsDTO shopOrderEsDTO = EntityUtil.copy(record, ShopOrderEsDTO.class);
                    CommodityOrderEsDTO commodityOrder = new CommodityOrderEsDTO();
                    List<CommodityOrderDetailEsDTO> commodityOrderDetailList = new ArrayList<>();
                    CommodityOrderDetailEsDTO orderDetailEsDTO = new CommodityOrderDetailEsDTO();
                    if (CollectionUtils.isNotEmpty(record.getCommodityOrder().getCommodityOrderDetailList()) && record.getCommodityOrder().getCommodityOrderDetailList().size() > 0) {
                        for (com.ctshk.rpc.user.dto.es.CommodityOrderDetailEsDTO detailEsDTO : record.getCommodityOrder().getCommodityOrderDetailList()) {
                            orderDetailEsDTO.setCommodityName(detailEsDTO.getCommodityName());
                            orderDetailEsDTO.setCommodityCostAttributeName(detailEsDTO.getCommodityCostAttributeName());
                            orderDetailEsDTO.setCommodityPictureUrl(detailEsDTO.getCommodityPictureUrl());
                            orderDetailEsDTO.setCommodityPrice(detailEsDTO.getCommodityPrice());
                            orderDetailEsDTO.setNumber(detailEsDTO.getNumber());
                            commodityOrderDetailList.add(orderDetailEsDTO);
                        }
                    }
                    commodityOrder.setCommodityOrderDetailList(commodityOrderDetailList);
                    shopOrderEsDTO.setCommodityOrder(commodityOrder);
                    orderEsDTOList.add(shopOrderEsDTO);
                }
//                List<ShopOrderEsDTO> orderEsDTOList = EntityUtil.copyList(pageResponseResult.getData().getRecords(), ShopOrderEsDTO.class);


                PageResponse<ShopOrderEsDTO> pageResponse = new PageResponse<ShopOrderEsDTO>(orderEsDTOList, iPage.getCurrent() == 1, orderEsDTOList.size() <= (req.getPageNo() * req.getPageSize()), orderEsDTOList.size(), req.getPageNo(), req.getPageSize());
                return Result.success(pageResponse);
            }
        } catch (Exception e) {
            log.error("【中旅商城--app小店--获取es订单数据错误】--- 错误信息：{}", e.getMessage());
        }
        log.info("【中旅商城--app小店--客户订单--end】");
        PageResponse<ShopOrderEsDTO> pageResponse = new PageResponse<ShopOrderEsDTO>(null, iPage.getCurrent() == 1, iPage.getTotal() <= (req.getPageNo() * req.getPageSize()), iPage.getTotal(), req.getPageNo(), req.getPageSize());
        return Result.success(pageResponse);
    }
}
